<template>
  <!--  物料分组管理查询条件-->
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="组别名称" prop="groupName">
        <el-input
          v-model="queryParams.groupName"
          placeholder="请输入组别名称模糊查询"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
          @blur="trimOnBlur"
        />
      </el-form-item>
      <el-form-item label="组别状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择组别状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd()"
          v-hasPermi="['system:groups:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <!--物料分组列表-->
    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="groupList"
      :highlight-current-row="true"
      row-key="groupId"
      stripe
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="groupName" label="组别名称" width="400"/>
      <el-table-column prop="orderNum" label="显示顺序" v-if="columns[0].visible"/>
      <el-table-column label="组别状态" align="center" prop="status" v-if="columns[1].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200" v-if="columns[2].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="400" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:groups:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:groups:add']"
          >新增
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:groups:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>




    <!-- 添加或修改物料分组管理对话框 -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="title" :visible.sync="open" width="400px" append-to-body :close-on-click-modal=false>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级组别" prop="parentId">
              <treeselect v-model="form.parentId" :options="groupsOptions" :normalizer="normalizer"
                          placeholder="选择上级组件（如根节点请留空）"/>
            </el-form-item>
            <el-form-item label="组别名称" prop="groupName">
              <el-input v-model="form.groupName" placeholder="请输入组别名称" @blur="trimOnBlur" clearable/>
            </el-form-item>
            <el-form-item label="显示顺序" prop="orderNum">
              <el-input v-model="form.orderNum" placeholder="请输入显示顺序" @blur="trimOnBlur" clearable/>
            </el-form-item>
            <el-form-item label="组别状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listWmsItemGroups,
    getWmsItemGroups,
    addWmsItemGroups,
    updateWmsItemGroups,
    delWmsItemGroups,
    exportGroups,
    listGroupsExcludeChild
  } from "@/api/wms/wmsItemGroups";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import { trimOnBlur } from '@/utils/form'
  export default {
    dicts: ['sys_normal_disable'],
    name: "Groups",
    components: {Treeselect},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 物料分组管理表格数据
        groupList: [],
        // 部门树选项
        groupsOptions: [],
        //系统开关
        sys_normal_disable: [],
        // 是否展开，默认全部展开
        isExpandAll: true,
        // 重新渲染表格状态
        refreshTable: true,
        // 是否展开
        expand: false,
        // 状态数据字典
        statusOptions: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          parentId: null,
          ancestors: null,
          groupName: null,
          orderNum: null,
          leader: null,
          phone: null,
          email: null,
          status: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          groupName: [
            {required: true, message: "请输入组别名称", trigger: "change"}
          ],
        },
        columns: [
          {key: 0, label: `显示顺序`, visible: true},
          {key: 1, label: `组别状态`, visible: true},
          {key: 2, label: `创建时间`, visible: true},
        ],
      };
    },
    created() {
      this.getList();
      //获取系统开关数据
      this.getDicts("sys_normal_disable").then(response => {
        this.statusOptions = response.data;
      });
    },
    methods: {
      trimOnBlur,
      /** 查询物料分组管理列表 */
      getList() {
        this.loading = true;
        listWmsItemGroups(this.queryParams).then(response => {
          this.groupList = this.handleTree(response.data, "groupId");
          this.loading = false;
        });
      },
      /** 转换组别数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.groupId,
          label: node.groupName,
          children: node.children
        };
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          groupId: null,
          parentId: null,
          ancestors: null,
          groupName: null,
          orderNum: null,
          leader: null,
          phone: null,
          email: null,
          status: "0",
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /**多选框选中数据*/
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.groupId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        this.reset();
        if (row != null) {
          this.form.parentId = row.groupId
          console.log(this.form.parentId)
        }
        this.open = true
        this.title = "添加组别"
        // this.form.parentId = 0
        listWmsItemGroups().then(response => {
          this.groupsOptions = this.handleTree(response.data, "groupId")
        });
      },
      /** 展开/折叠操作 */
      toggleExpandAll() {
        this.refreshTable = false;
        this.isExpandAll = !this.isExpandAll;
        this.$nextTick(() => {
          this.refreshTable = true;
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        getWmsItemGroups(row.groupId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改组别";
        });
        listGroupsExcludeChild(row.groupId).then(response => {
          this.groupsOptions = this.handleTree(response.data, "groupId");
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.groupId != null) {
              updateWmsItemGroups(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              if (!this.form.parentId) this.form.parentId = 0
              addWmsItemGroups(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const groupIds = row.groupId || this.ids;
        this.$confirm('是否确认删除组别名称为"' + row.groupName + '"的物料分组?', "删除确认", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delWmsItemGroups(groupIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有物料分组管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportGroups(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {
        });
      }
    }
  };
</script>
